package com.agileai.portal.portlets.content;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.ProcessAction;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ValidatorException;
import javax.servlet.http.HttpServletRequest;

import com.agileai.domain.DataRow;
import com.agileai.domain.KeyNamePair;
import com.agileai.hotweb.common.StringTemplateLoader;
import com.agileai.portal.bizmoduler.wcm.InfomationManage;
import com.agileai.portal.driver.GenericPotboyPortlet;
import com.agileai.portal.driver.Resource;
import com.agileai.portal.driver.common.PortletRequestHelper;
import com.agileai.portal.driver.common.PreferenceException;
import com.agileai.portal.driver.common.PreferencesHelper;
import com.agileai.portal.driver.common.PreferencesWrapper;
import com.agileai.portal.portlets.PortletCacheManager;
import com.agileai.util.DateUtil;
import com.agileai.util.ListUtil;
import com.agileai.util.MapUtil;
import com.agileai.util.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;

public class ContentViewPortlet extends GenericPotboyPortlet {
	protected static final String ContentIdParamModeByParse = "byParse";
	protected static final String ContentIdParamModeByRetrieve = "byRetrieve";
	
	@RenderMode(name = "view")
	public void view(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences =  PreferencesHelper.getPublicPreference(request);
		String minHeight = preferences.getValue("minHeight", null);
		String templateId = preferences.getValue("templateId", null);
		String contentIdParamKey = preferences.getValue("contentIdParamKey", null);
		String contentIdParamMode = preferences.getValue("contentIdParamMode", ContentIdParamModeByRetrieve);
		String observeViewCount  = preferences.getValue("observeViewCount", "Y");
		
		if (!StringUtil.isNullOrEmpty(minHeight) && !StringUtil.isNullOrEmpty(templateId) 
				&& !StringUtil.isNullOrEmpty(contentIdParamKey) ){
			request.setAttribute("isSetting", "Y");
		}else{
			request.setAttribute("isSetting", "N");
		}
		
		String isSetting = (String)request.getAttribute("isSetting");
		if ("Y".equals(isSetting)){
			String contentIdDefValue = preferences.getValue("contentIdDefValue", null);
			String contentId =  null;
			HttpServletRequest httpServletRequest = PortletRequestHelper.getRequestContext(request).getServletRequest();
			if (ContentIdParamModeByRetrieve.equals(contentIdParamMode)){
				contentId = httpServletRequest.getParameter(contentIdParamKey);				
			}else{
				contentId = (String)httpServletRequest.getAttribute(contentIdParamKey);
			}
			if (StringUtil.isNullOrEmpty(contentId)){
				contentId = contentIdDefValue;
			}
			if (StringUtil.isNullOrEmpty(contentId)){
				request.setAttribute("content", "content is not defined,please check it !");
			}else{
				InfomationModel infomationModel = this.retrieveInfomation(preferences,contentId);
				try {
					String urlPrefix = PortletCacheManager.buildDataURLPefix(request);
					StringWriter writer = new StringWriter();
					String tempateURL = urlPrefix+"/resource?PortletTemptProvider&actionType=retrieveContent&contentId="+templateId;
					String template = this.retrieveData(preferences, tempateURL);
//					String template = this.retrieveData(preferences, dataURL);
					generate(infomationModel, template, writer);
					request.setAttribute("content", writer.toString());
				} catch (Exception e) {
					logger.error(e.getLocalizedMessage(), e);
				}
			}
			request.setAttribute("infomationId", contentId);			
		}
		request.setAttribute("observeViewCount", observeViewCount);
		request.setAttribute("minHeight", minHeight);
		super.doView(request, response);
	}

	@RenderMode(name = "edit")
	public void edit(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String minHeight = preferences.getValue("minHeight", "400");
		String templateId = preferences.getValue("templateId", null);
		String contentIdParamKey = preferences.getValue("contentIdParamKey", "contentId");
		String contentIdParamMode = preferences.getValue("contentIdParamMode", ContentIdParamModeByRetrieve);
		String contentIdDefValue = preferences.getValue("contentIdDefValue", null);
		String observeViewCount  = preferences.getValue("observeViewCount", "Y");
		String observeReviewCount  = preferences.getValue("observeReviewCount", "Y");
		
		request.setAttribute("minHeight", minHeight);
		request.setAttribute("templateId", templateId);
		request.setAttribute("contentIdParamKey",contentIdParamKey);
		request.setAttribute("contentIdDefValue",contentIdDefValue);
		request.setAttribute("contentIdParamMode", contentIdParamMode);
		request.setAttribute("observeViewCount", observeViewCount);
		request.setAttribute("observeReviewCount", observeReviewCount);
		super.doEdit(request, response);
	}

	@ProcessAction(name = "saveConfig")
	public void saveConfig(ActionRequest request, ActionResponse response)
			throws ReadOnlyException, PortletModeException, ValidatorException,
			IOException, PreferenceException {
		String minHeight = request.getParameter("minHeight");
		String templateId = request.getParameter("templateId");
		String contentIdParamKey = request.getParameter("contentIdParamKey");
		String contentIdParamMode = request.getParameter("contentIdParamMode");
		String contentIdDefValue = request.getParameter("contentIdDefValue");
		String observeViewCount = request.getParameter("observeViewCount");
		String observeReviewCount = request.getParameter("observeReviewCount");
		
		PreferencesWrapper preferWapper = new PreferencesWrapper();		
		preferWapper.setValue("minHeight", minHeight);
		preferWapper.setValue("templateId", templateId);
		preferWapper.setValue("contentIdParamKey", contentIdParamKey);
		preferWapper.setValue("contentIdDefValue", contentIdDefValue);
		preferWapper.setValue("contentIdParamMode", contentIdParamMode);
		preferWapper.setValue("observeViewCount", observeViewCount);
		preferWapper.setValue("observeReviewCount", observeReviewCount);
		
		PreferencesHelper.savePublicPreferences(request, preferWapper.getPreferences());	
		response.setPortletMode(PortletMode.VIEW);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void generate(InfomationModel infomationModel,String template,StringWriter writer) {
		String encoding = "utf-8";
		try {
        	Configuration cfg = new Configuration();
        	cfg.setTemplateLoader(new StringTemplateLoader(template));  
        	cfg.setEncoding(Locale.getDefault(), encoding);
            cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
        	Template temp = cfg.getTemplate("");
        	temp.setEncoding(encoding);
            Map root = new HashMap();
            root.put("model",infomationModel);
            temp.process(root, writer);
            writer.flush();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	private String retrieveData(PortletPreferences preferences,String dataURL) throws Exception{
		String ajaxData = "";
		String cacheMinutes = (String)preferences.getValue("cacheMinutes",defaultCacheMinutes);
		String isCache = preferences.getValue("isCache", defaultIsCache);
		ajaxData = PortletCacheManager.getOnly().getCachedData(isCache, dataURL, cacheMinutes);
		return ajaxData;
	}
	
	private InfomationModel retrieveInfomation(PortletPreferences preferences,String infomationId){
		InfomationModel result = null;
		InfomationManage infomationManage = this.lookupService(InfomationManage.class);
		DataRow row = infomationManage.getContentRecord(infomationId);
		if (!MapUtil.isNullOrEmpty(row)){
			result = new InfomationModel();
			result.setId(row.stringValue("INFO_ID"));
			result.setTitle(row.stringValue("INFO_TITLE"));
			
			int observeViewCount = infomationManage.findReadCount(infomationId);
			result.setReadCount(String.valueOf(observeViewCount));
			
			result.setContent(row.stringValue("INFO_CONTENT"));
			result.setAuthor(row.stringValue("INFO_PUBLISHER_NAME"));
			Date date = (Date)row.get("INFO_PUBLISH_TIME");
			if (date != null){
				result.setPublishTime(DateUtil.format(DateUtil.YYMMDDHHMI_HORIZONTAL, date));;				
			}
			
			String observeReviewCount  = preferences.getValue("observeReviewCount", "Y");
			if ("Y".equals(observeReviewCount)){
				int reviewCount = infomationManage.findInfoReviewCount(infomationId);
				result.setReviewCount(reviewCount);				
			}
			
			List<DataRow> records = infomationManage.findInfomationKeyWordsRelations(infomationId);
			if (!ListUtil.isNullOrEmpty(records)){
				for (int i=0;i < records.size();i++){
					DataRow tempRow = records.get(i);
					String wordId = tempRow.stringValue("WORD_ID");
					String wordName = tempRow.stringValue("WORD_NAME");
					KeyNamePair keyNamePair = new KeyNamePair();
					keyNamePair.setKey(wordId);
					keyNamePair.setValue(wordName);
					result.getKeywords().add(keyNamePair);
				}
			}
		}
		return result;
	}
	
	@Resource(id="increaseReadCount")
	public void increaseReadCount(ResourceRequest request, ResourceResponse response)
			throws PortletException, IOException {
		String ajaxData = "";
		try {
			String infomationId = request.getParameter("infomationId");
			InfomationManage infomationManage = this.lookupService(InfomationManage.class);
			infomationManage.increaseReadCount(infomationId);
		} catch (Exception e) {
			this.logger.error("获取取数据失败getAjaxData", e);
		}
		PrintWriter writer = response.getWriter();
		writer.print(ajaxData);
		writer.close();
	}
}
